package stock.nordnet;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import stock.credentials.GoogleFr;
import stock.credentials.Login;

import com.google.gdata.client.spreadsheet.FeedURLFactory;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CellEntry;
import com.google.gdata.data.spreadsheet.CellFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;

public class FondDataSheetUpdater {
    private final Login googleFr = new GoogleFr();

    public void update(String value) {
        try {
            SpreadsheetService service = new SpreadsheetService(
                    "NordnetDirektParser");
            service.setUserCredentials(googleFr.getUser(),
                    googleFr.getPassword());

            FeedURLFactory factory = FeedURLFactory.getDefault();
            SpreadsheetFeed spreadFeed = null;

            spreadFeed = service.getFeed(factory.getSpreadsheetsFeedUrl(),
                    SpreadsheetFeed.class);

            SpreadsheetEntry spreadSheet = null;
            for (SpreadsheetEntry entry : spreadFeed.getEntries()) {
                if (entry.getTitle().getPlainText().equals("FondData")) {
                    spreadSheet = entry;
                    break;
                }
            }

            URL cellFeedUrl = spreadSheet.getWorksheets().get(0)
                    .getCellFeedUrl();
            CellFeed cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);

            int firstFreeRow = 1;
            for (CellEntry cell : cellFeed.getEntries()) {
                firstFreeRow = cell.getCell().getRow() + 1;
            }
            CellEntry valueCell = new CellEntry(firstFreeRow, 2, value);
            CellEntry dateCell1 = new CellEntry(firstFreeRow, 1,
                    getCurrentDate());
            CellEntry dateCell2 = new CellEntry(firstFreeRow, 3,
                    getCurrentDate());
            CellEntry calcCell = new CellEntry(firstFreeRow, 4, "=SUM(B"
                    + firstFreeRow + "-B1)/B1");

            service.insert(cellFeedUrl, valueCell);
            service.insert(cellFeedUrl, dateCell1);
            service.insert(cellFeedUrl, dateCell2);
            service.insert(cellFeedUrl, calcCell);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e1) {
            }
            update(value);
        }
    }

    private String getCurrentDate() {
        Calendar currentTime = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH.mm.ss");
        return dateFormat.format(currentTime.getTime());

    }
}
